<template>
    <div class="upload">
        <div>小区图片</div>
      <el-upload
        action="#"
        list-type="picture-card"
        :show-file-list="true"
        :http-request="httpRequest"
        :before-upload="beforeUpload"
        :on-remove="onRemove"
        :on-preview="onPreview"
        :file-list="fileList"
        :class="{disabled:fileList.length===1}"
      >
        <i class="el-icon-plus" />
      </el-upload>
      <el-dialog append-to-body title="预览图片" :visible.sync="showDialog">
        <img :src="imgUrl" alt="">
      </el-dialog>
    </div>
  
  </template>
  <script>
  import { upload } from '@/api/upLoad'
  export default {
    props: {
      value: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        fileList: [],
        imgUrl: '',
        showDialog: false
      }
    },
    watch: {
      value: {
        handler() {
          this.fileList = this.value ? [{ url: this.$webURL + this.value }] : []
        },
        immediate: true // 一开始就执行
      }
    },
    methods: {
      // 上传成功
      // onSuccess(val) {
      //   console.log(val)
      // },
      // 自定义上传
      async httpRequest({ file }) {
      // 1. 实例fd
        const fd = new FormData()
        // 2. 注入文件信息
        fd.append('file', file)
        // 3. 发生请求
        const res = await upload(fd) // 传入fd实例
        // console.log(res);
        // 4. 将服务器返回的存储地址给图片字段
        // 数据传递给外面
        this.$emit('input', res.data.url)
        // 5. 将本地图片地址替换成线上地址
        this.fileList = [{ url: this.$webURL + res.data.url }]
      },
      // 图片移除
      onRemove() {
        this.fileList = []
        this.$emit('input', '')
      },
      // 预览
      onPreview(val) {
        this.imgUrl = val.url
        this.showDialog = true
      },
      // 上传前
      beforeUpload(file) {
      // 检查大小  1G = 1024MB  1MB = 1024KB   1kb = 1024b
        if ((file.size / 1024 / 1024) > 2) {
          this.$message.warning('体积不允许超过2M')
          return false
        }
        // 检查类型
        const typeList = ['image/jpeg', 'image/png', 'image/jpg', 'image/gif']
        if (!typeList.includes(file.type)) {
          this.$message.warning('格式不正确')
          return false
        }
        // 通过了
        return true
      }
    }
  }
  </script>
  
  <style lang="scss" scoped>
  .upload{
    padding: 40px;
  }
  .disabled{
    ::v-deep .el-upload--picture-card{
      display: none;
    }
  }
  </style>
  